package com.aizuda.easyManagerTool.config.socket;

import cn.hutool.json.JSONUtil;
import com.aizuda.easyManagerTool.domain.dto.socket.SocketMessageDTO;
import com.aizuda.easyManagerTool.service.socket.impl.SocketEventStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;

@Component
@Slf4j
public class WebSSHSocketHandler extends TextWebSocketHandler {

    @Resource
    SocketEventStrategy socketEventStrategy;
    /**
     * socket 建立成功事件
     * @param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String token = webSocketSession.getAttributes().get("token").toString();
        log.debug("建立链接,{}",token);
        socketEventStrategy.onConnect(token,webSocketSession);
    }

    /**
     * 接收消息事件
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage webSocketMessage) throws Exception {
        // 消息内容
        Object payload = webSocketMessage.getPayload();
        String token = webSocketSession.getAttributes().get("token").toString();
        SocketMessageDTO socketMessageDTO = JSONUtil.toBean(payload.toString(), SocketMessageDTO.class);
        socketEventStrategy.onMessage(token,webSocketSession,socketMessageDTO);
    }

    /**
     * socket 断开连接时
     * @param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession,CloseStatus closeStatus) throws Exception {
        String token = webSocketSession.getAttributes().get("token").toString();
        socketEventStrategy.onClose(token,webSocketSession,closeStatus);
        log.debug("用户离开,{}",token);
        webSocketSession.close();
    }


}
